import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  LoggerService,
} from '@nestjs/common';
import { Request, Response } from 'express';
import * as requestIp from 'request-ip';
interface myError {
  readonly status: number;
  readonly statusCode?: number;
  readonly message?: string;
}
@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  constructor(private loggger: LoggerService) {}
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : (exception as myError)?.status ||
          (exception as myError)?.statusCode ||
          HttpStatus.INTERNAL_SERVER_ERROR;
    const message =
      (exception as any)?.response?.message ||
      (exception as myError)?.message ||
      `${exception}`;
    const clientIp = requestIp.getClientIp(request);
    this.loggger.error(message, exception.stack);

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: message,
      clientIp,
    });
  }
}
